{
  Plug-in component shader: CelShader

  Based on modo's SDK example celShader.cpp which is:

  Copyright (c) 2008-2012 Luxology LLC

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.   Except as contained
  in this notice, the name(s) of the above copyright holders shall not be
  used in advertising or otherwise to promote the sale, use or other dealings
  in this Software without prior written authorization.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.
}

{
  Copyright (c) 2012 David Ballesteros and Jameel Halabi

  This unit is part of the BLAISEmodo wrapper,
  which is licensed under the BSD 2-Clause license (see licenses/license.txt).
}

unit Plugin;

{$mode objfpc}{$H+}

{$asmmode intel}

interface

uses
  Lx_Result,
  Lx_Server,
  Lx_Shade,
  Lx_Vector,
  Lx_Log,
  Lx_Package,
  Lx_Value,
  Lx_Action,
  Lx_VMath;

const
  SRVs_CEL_MATR          = 'bmCelShader'                ;
  SRVs_CEL_MATR_ITEMTYPE = 'material.' + SRVs_CEL_MATR;

type
  {
    Cel material & shader
    The cel shader is implemented as a custom material.
    Custom materials have the ability to set material attributes
    and to contribute to shading after the base shader has been evaluated
  }

  { TCelMaterial }

  TCelMaterial = class(TLxCustomMaterial)
    FRendData : record
      DiffBands ,
      SpecBands ,
      ReflBands : Integer;

      DiffLevel ,
      SpecLevel ,
      ReflLevel : Double ;
    end;
    // Indices to each data channel in RendData
    FIndex : array [0..5] of UInt32;

    function  SetupChannels
              (    AddChan : IUnknown           ) : LxResult      ; override;
    function  LinkChannels
              (    Eval    : IUnknown           ;
                   Item    : IUnknown           ) : LxResult      ; override;
    function  ReadChannels
              (    Attr    : IUnknown           ;
               out Data                         ) : LxResult      ; override;
    procedure ShaderEvaluate
              (    Vector  : IUnknown           ;
                   RayObj  : IUnknown           ;
                   SCmp    : PLXpShadeComponents;
                   SOut    : PLXpShadeOutput    ;
                   Data    : Pointer            )                 ; override;
    function  SetOpaque
              (    Opaque  : PInteger           ) : LxResult      ; override;
  end;

implementation

function Floor(X : Single) : Single; inline;
begin
  if X >= 0 then
    Result := Trunc(X)
  else
    Result := Trunc(X) - 1;
end;

function FVectorNormalize(var V : LXtFVector) : Single; inline;
begin
  Result := TVMathF.LXx_VDOT(V, V);

  if Result <= 0 then
    Result := -1
  else
  begin
    Result := Sqrt(Result);
    TVMathF.LXx_VSCL(V, 1.0 / Result);
  end;
end;

procedure FVectorQuantize(  var Vec   : LXtFVector;
                          const Bnd   : Integer   ;
                          const Level : Single    ) ; inline;
var
  Vec0 : array [0..2] of Single;
  Len  : Single;
begin
  TVMathF.LXx_VCPY(Vec0, Vec);
  Len := FVectorNormalize(Vec0);

  TVMathF.LXx_VSCL3(Vec, Vec0,
                   (Floor(Len * (Bnd - 1)) + Level) / Single(Bnd)
                   );
end;

{
  Setup channels for the item type.
}
function TCelMaterial.SetupChannels(AddChan : IUnknown) : LxResult;
begin
  with ILxAddChannel(AddChan) do
  begin
    NewChannel('diffBands', LXsTYPE_INTEGER);
    SetDefault(0.0, 3);

    NewChannel('specBands', LXsTYPE_INTEGER);
    SetDefault(0.0, 0);

    NewChannel('reflBands', LXsTYPE_INTEGER);
    SetDefault(0.0, 0);

    NewChannel('diffLevel', LXsTYPE_PERCENT);
    SetDefault(0.50, 0);

    NewChannel('specLevel', LXsTYPE_PERCENT);
    SetDefault(0.50, 0);

    NewChannel('reflLevel', LXsTYPE_PERCENT);
    SetDefault(0.50, 0);
  end;

  Result := LXe_OK;
end;

{
  Attach to channel evaluations.
  This gets the indices for the channels in attributes.
}
function TCelMaterial.LinkChannels(Eval : IUnknown;
                                   Item : IUnknown) : LxResult;
begin
  with ILxEvaluation(Eval) do
  begin
    AddChannelName(Item, 'diffBands', LXfECHAN_READ, @FIndex[0]);
    AddChannelName(Item, 'specBands', LXfECHAN_READ, @FIndex[1]);
    AddChannelName(Item, 'reflBands', LXfECHAN_READ, @FIndex[2]);
    AddChannelName(Item, 'diffLevel', LXfECHAN_READ, @FIndex[3]);
    AddChannelName(Item, 'specLevel', LXfECHAN_READ, @FIndex[4]);
    AddChannelName(Item, 'reflLevel', LXfECHAN_READ, @FIndex[5]);
  end;

  Result := LXe_OK;
end;

{
  Read channel values which may have changed.
}
function TCelMaterial.ReadChannels(    Attr : IUnknown;
                                   out Data           ) : LxResult;
begin
  with ILxAttributes(Attr), FRendData do
  begin
    GetInt(FIndex[0], @DiffBands);
    GetInt(FIndex[1], @SpecBands);
    GetInt(FIndex[2], @ReflBands);
    GetFlt(FIndex[3], @DiffLevel);
    GetFlt(FIndex[4], @SpecLevel);
    GetFlt(FIndex[5], @ReflLevel);
  end;

  Result := LXe_OK;
end;

{
  Evaluate the color at a spot.
}
procedure TCelMaterial.ShaderEvaluate(Vector : IUnknown           ;
                                      RayObj : IUnknown           ;
                                      SCmp   : PLXpShadeComponents;
                                      SOut   : PLXpShadeOutput    ;
                                      Data   : Pointer            ) ;
begin
  {
    Quantize each component with the bands and level settings
  }
  with FRendData, SCmp^ do
  begin
    if DiffBands <> 0 then FVectorQuantize(Diff, DiffBands, DiffLevel);
    if SpecBands <> 0 then FVectorQuantize(Spec, SpecBands, SpecLevel);
    if ReflBands <> 0 then FVectorQuantize(Refl, ReflBands, ReflLevel);
  end;

  // Update final output color
  with SOut^, SCmp^ do
  begin
    Color := Diff + Spec + Refl + Tran + Subs + Lumi;
  end;
end;

{
  Since the cel shader is modifying the results of another shader,
  it cannot be opaque.
}
function TCelMaterial.SetOpaque(Opaque : PInteger) : LxResult;
begin
  Opaque^ := 0;

  Result := LXe_OK;
end;

initialization
  AddServer(SRVs_CEL_MATR, TCelMaterial, [LXsSRV_USERNAME    , 'BM Cel Material',
                                          LXsSRV_LOGSUBSYSTEM, 'comp-shader'   ]);

end.

